<template>
  <div class="top">
    <tiny-button type="primary" @click="visible = true">添加账号</tiny-button>
    <tiny-select v-model="value" style="width:300px;margin-left: 20px;" @change="search">
      <tiny-option v-for="item in options" :key="item.id" :label="item.name" :value="item.name">
      </tiny-option>
    </tiny-select>
  </div>
  <div class="demo-tag-create">
    <span v-for="(tag, index) in dynamicTags" :key="tag.id">
      <tiny-tooltip v-if="tagIndex !== index" effect="dark" :content="tag.name" placement="top"
                    :disabled="tag.length < 30">
        <tiny-tag closable @close="handleClose(index)" @dblclick="handleEdit(tag, index)">
          {{ tag.name.length > 20 ? `${tag.name.slice(0, 20)}...` : tag.name }}
        </tiny-tag>
      </tiny-tooltip>
      <tiny-input
          v-else
          v-model="inputValue1"
          ref="saveTagInput1Ref"
          size="small"
          @keyup.enter="InputConfirm1(true)"
          @blur="InputConfirm1(false)"
      >
      </tiny-input>
    </span>
    <tiny-input
        v-show="inputVisible"
        v-model="inputValue2"
        ref="saveTagInput2Ref"
        size="small"
        @keyup.enter="InputConfirm2"
        @blur="InputConfirm2"
    >
    </tiny-input>
    <tiny-button v-show="!inputVisible" class="button-new-tag" size="small" @click="showInput"> + New Tag</tiny-button>
  </div>
  <div class="main">
    <div class="left">
      <div class="box">
        <div class="item available" v-for="(item,i) in data?.available_accounts" :key="i">
          <div class="info">

            <span>{{ item.account }}</span>
            <tiny-tag style="margin-bottom: 10px">{{ item.kind }}</tiny-tag>
            <button @click="visible1 = true; account = item">
              <IconDel></IconDel>
            </button>
          </div>
          <div class="status">
            <span class="circle"></span> <span>空闲中</span>

          </div>
        </div>
      </div>

      <tiny-divider></tiny-divider>
      <div class="box">
        <div class="item" v-for="(item,i) in data?.unavailable_accounts" :key="i">
          <div class="info">
            <span @click="Go(item.account)">{{ item.account }}</span>
            <div>
              <tiny-tag>
                <IconStatistics style="margin-right: 3px;"></IconStatistics>
                验证码更新次数{{ item.count }}次
              </tiny-tag>
              <tiny-tag> 剩余{{ timeDifference(item.deadline) }}</tiny-tag>
            </div>
            <button type="success" @click="visible2 = true; account = item.account"> 强制下线</button>
          </div>
          <div class="status">
            <tiny-progress type="dashboard" :percentage="Math.round(timeDiff(item.deadline)*10/(item.time*6))"
                           :color="customColors" :width="120"></tiny-progress>

          </div>
        </div>
      </div>
    </div>
    <div class="right" style="position: relative">
      <p style="color:#909399">累计交易数量</p>
      <tiny-statistic
          :value="count"
          :value-style="{ 'color': '#3ac295' }"
          :title="{ value: '进行中', position: 'top' }"
      >
      </tiny-statistic>
      <button style="position: absolute; bottom: 20px;right: 20px" @click="excel">点我下载</button>
    </div>
  </div>

  <tiny-modal v-model="visible" type="confirm" show-footer :is-form-reset="false" :title="'添加账号'"

              @confirm="handleConfirm">
    <tiny-form :model="form" label-width="80px" label-position="left" :label-align="true" ref="formRef">
      <tiny-form-item label="账号" prop="account" required>
        <tiny-input v-model="form.account"></tiny-input>
      </tiny-form-item>
      <tiny-form-item label="种类" prop="kindId" required>
        <tiny-select v-model="form.kindId">
          <tiny-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
          </tiny-option>
        </tiny-select>
      </tiny-form-item>

    </tiny-form>
  </tiny-modal>
  <tiny-modal v-model="visible1" type="confirm" show-footer :is-form-reset="false" :title="'确定删除'"

              @confirm="Delete">

  </tiny-modal>
  <tiny-modal v-model="visible2" type="confirm" show-footer :is-form-reset="false" :title="'确定下线'"

              @confirm="offline">
  </tiny-modal>

</template>

<script setup lang="jsx">
import timeDifference from "../utils/timeDifference.js";
import {iconDel, iconStatistics} from '@opentiny/vue-icon'
import {Divider as TinyDivider, Statistic as TinyStatistic,} from '@opentiny/vue'
import {
  Progress as TinyProgress, Button as TinyButton, Form as TinyForm, Modal as TinyModal,
  FormItem as TinyFormItem, Notify
} from '@opentiny/vue'
import {ref, inject, onMounted, nextTick} from 'vue'
import * as XLSX from "xlsx";
import {useRouter} from "vue-router";
import {Select as TinySelect, Option as TinyOption, Modal} from '@opentiny/vue'

const value = ref('')
const router = useRouter()
const visible = ref(false)
const visible1 = ref(false)
const visible2 = ref(false)
const account = ref("")
const IconStatistics = iconStatistics()
const IconDel = iconDel()
const percentage = ref(10)
const count = ref(0)
const Go = (i) => {
  router.push({path: "/logs/" + i})
}
const options = ref([])
const customColors = ref([
  {color: '#f56c6c', percentage: 20},
  {color: '#e6a23c', percentage: 40},
  {color: '#5cb87a', percentage: 60},
  {color: '#1989fa', percentage: 80},
  {color: '#6f7ad3', percentage: 100}
])

const formRef = ref(null)
const axios = inject('axios')
const handleConfirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      form.value.kind = options.value.find(item => item.id == form.value.kindId).name
      axios.post("/account/add", form.value).then(res => {
        Notify({
          type: 'success',
          message: '添加成功',
          position: 'top-right'
        })
        window.location.reload()
      })
    } else {
      Notify({
        type: 'warning',
        message: '请完整填写信息',
        position: 'top-right'
      })
    }
  })
}

const form = ref({
  account: "",
  kind: "",
  kindId: 0
})
const data = ref({})
const Delete = () => {

  axios.delete("/account/delete?account=" + account.value.account).then(res => {
    Notify({
      type: 'success',
      message: '删除成功',
      position: 'top-right'
    })
    window.location.reload()
  })

}
const offline = () => {

  axios.get("/change/offline?account=" + account.value).then(res => {
    Notify({
      type: 'success',
      message: '下线成功',
      position: 'top-right'
    })
    window.location.reload()
  })

}
const search = () => {
  axios.get("/account/get_accounts?kind=" + value.value).then(res => {
    data.value = res.data.data
  }).catch(err => {
  })
}
onMounted(() => {
  axios.get("/kind").then(res => {
    options.value = res.data.data
  }).catch(err => {

  })
  search()
  axios.get("/code/sales").then(res => {

    count.value = res.data.data
  }).catch(err => {

  })
  axios.get("/kind").then(res => {

    dynamicTags.value = res.data.data
  }).catch(err => {

  })
})


function timeDiff(targetDate) {
  const now = new Date();
  const time = new Date(targetDate)
  const difference = time.getTime() - now.getTime();
  return difference / 60000;

}

const excel = () => {
  axios.get("code/codes").then(res => {
    const workbook = XLSX.utils.book_new();
// 创建一个新的工作表
    const worksheet1 = XLSX.utils.json_to_sheet(res.data.data.filter(i => i.time == 12));
    const worksheet2 = XLSX.utils.json_to_sheet(res.data.data.filter(i => i.time == 24));
// 将工作表附加到工作簿，并将工作表命名为students
    XLSX.utils.book_append_sheet(workbook, worksheet1, "12小时时长码");
    XLSX.utils.book_append_sheet(workbook, worksheet2, "24小时时长码");

// 导出工作簿，并命名导出文件名为Presidents.xlsx
    var currentTime = new Date();
    XLSX.writeFile(workbook, currentTime + ".xlsx");
  }).catch(err => {
  })
}


const dynamicTags = ref([])
const inputVisible = ref(false)
const inputValue1 = ref('')
const inputValue2 = ref('')
const tagIndex = ref(-1)
const saveTagInput2Ref = ref()
const saveTagInput1Ref = ref()

function handleClose(index) {
  Modal.confirm({
    title: '确认删除',
    message: '确定要删除该标签吗？',
  }).then(re => {
    axios.delete("kind/delete?id=" + dynamicTags.value[index].id).then(res => {
      dynamicTags.value.splice(index, 1)
    }).catch(err => {
        }
    )
  })
  //dynamicTags.value.splice(index, 1)
}

function showInput() {
  inputVisible.value = true
  nextTick(() => {
    saveTagInput2Ref.value.focus()
  })
}

// 修改已有标签确认
function InputConfirm1(sure) {
  if (sure) {
    axios.get("kind/update?id=" + dynamicTags.value[tagIndex.value].id + "&name=" + inputValue1.value).then(res => {
      dynamicTags.value[tagIndex.value] = {id: dynamicTags.value[tagIndex.value].id, name: inputValue1.value}
      tagIndex.value = -1
    })
    //dynamicTags.value[tagIndex.value] ={id: dynamicTags.value[tagIndex.value].id, name: inputValue1.value}
  } else
    tagIndex.value = -1
}

// 增加新标签确认
function InputConfirm2() {

  if (inputValue2.value) {
    axios.get("kind/add?name=" + inputValue2.value).then(res => {
      dynamicTags.value.push({id: dynamicTags.value.length + 1, name: inputValue2.value})
      inputVisible.value = false
      inputValue2.value = ''
    }).catch(err => {
    })
  } else {
    inputVisible.value = false
    inputValue2.value = ''
  }

}

// 双击编辑标签
function handleEdit(tag, index) {
  tagIndex.value = index
  inputValue1.value = tag
  nextTick(() => {
    saveTagInput1Ref.value[0].focus()
  })
}
</script>

<style scoped>

</style>
<style lang="less" scoped>
.top {
  margin: 20px;
  display: flex;
  justify-content: flex-start;
}

@media (min-width: 570px) {
  .main {
    flex-direction: row;
    width: 90%;
    justify-content: space-between;
  }

  .left {
    width: 60%;
  }

  .right {
    width: 30%;
    margin-left: 30px;
  }
}

@media (max-width: 560px) {
  .main {
    flex-direction: column;
    width: 97%;

    .left, .right {
      margin: 20px auto;
      width: 100%;
      box-sizing: border-box;
    }
  }

}

.main {
  box-sizing: border-box;
  font-size: 14px;
  margin: 20px auto;
  display: flex;

  button {
    width: 100px;
    height: 30px;
    color: #ffffff;
    border-radius: 4px;
    font-size: 12px;
    background-color: #5e7ce0;
    border: 1px transparent solid;
  }

  .left {
    background-color: #ffffff;
    padding: 20px;
    box-shadow: 0 1px 10px #c2c2c2;


    .box {

      color: #555666;
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      flex-wrap: wrap;

      .item {
        // width: 400px;
        box-shadow: 0 0 10px #c2c2c2;
        margin: 10px;
        padding: 10px;
        display: flex;
        justify-content: space-between;


        .info {
          width: auto;
          display: flex;
          flex-direction: column;


          .tiny-tag {
            font-size: 12px;
            margin: 10px 10px 10px 0;
          }


        }

        .status {
          height: 100%;
          display: flex;
          align-items: center;


        }

        .circle {
          display: block;
          width: 10px;
          height: 10px;
          border-radius: 50%;
          background-color: red;
          margin: 10px;
        }


      }

      .available {
        button {
          width: 30px;
          height: 30px;
          border-radius: 50%;

        }

        .circle {
          background-color: green;
        }

        width: 200px;
      }
    }

  }

  .right {
    background-color: #ffffff;
    padding: 20px;
    box-shadow: 0 1px 10px #c2c2c2;
    height: 200px;
  }

}

.demo-tag-create .tiny-tag {
  margin-left: 10px;
}

.demo-tag-create .tiny-button.button-new-tag {
  margin-left: 10px;
  height: 22px;
  line-height: 20px;
  padding-top: 0;
  padding-bottom: 0;
}

.demo-tag-create .tiny-input {
  width: 90px;
  height: 22px;
  line-height: 20px;
  margin-left: 10px;
  vertical-align: middle;
}

.demo-tag-create .tiny-input .tiny-input__inner {
  height: 22px;
  line-height: 20px;
}


</style>